<script setup lang="tsx">
import { Form, FormSchema } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { useValidator } from '@/hooks/web/useValidator'
import { useI18n } from '@/hooks/web/useI18n'
import { createRoleApi, updateRoleApi } from '@/api/role'

const { t } = useI18n()

const { required, lengthRange } = useValidator()

const props = defineProps({
  currentRow: {
    type: Object as PropType<any>,
    default: () => null
  }
})

const formSchema = ref<FormSchema[]>([
  {
    field: 'name',
    label: t('role.roleName'),
    component: 'Input'
  },
  {
    field: 'remark',
    label: t('userDemo.remark'),
    component: 'Input'
  }
])

const rules = reactive({
  name: [required()],
  remark: [lengthRange({ min: 0, max: 50 })]
})

const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose } = formMethods

const createRole = async (data: any) => {
  const res = await createRoleApi(data)
  return res.code === 200
}

const updateRole = async (data: any) => {
  const res = await updateRoleApi(data)
  return res.code === 200
}

const submit = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log(err)
  })
  if (valid) {
    const formData = await getFormData()
    if (formData.id) {
      // 修改
      return updateRole(formData)
    } else {
      // 新增
      return createRole(formData)
    }
  }
}

watch(
  () => props.currentRow,
  (currentRow) => {
    if (!currentRow) return
    setValues(currentRow)
  },
  {
    deep: true,
    immediate: true
  }
)

defineExpose({
  submit
})
</script>

<template>
  <Form :isCol="false" :rules="rules" @register="formRegister" :schema="formSchema" />
</template>
